package com.heima.comment.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.comment.pojos.ApComment;
import com.alibaba.fastjson.JSON;
import com.heima.comment.pojos.ApComment;
import com.heima.comment.pojos.ApCommentLike;
import com.heima.comment.pojos.CommentVo;
import com.heima.comment.service.CommentService;
import com.heima.feign.article.IArticleClient;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmCommentDto;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.ApUserThreadLocalUtil;
import com.heima.common.constants.HotArticleConstants;
import com.heima.feign.user.IUserClient;
import com.heima.feign.wemedia.IWemediaClient;
import com.heima.model.comment.dtos.CommentDto;
import com.heima.model.comment.dtos.CommentLikeDto;
import com.heima.model.comment.dtos.SaveCommentDto;
import com.heima.model.comment.dtos.ScanCommentContentDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.mess.UpdateArticleMess;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import com.heima.feign.article.IArticleClient;
import com.heima.model.article.pojos.ApArticleConfig;
import com.heima.model.comment.dtos.CommentSaveDto;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private IWemediaClient iWemediaClient;
    @Autowired
    private MongoTemplate  mongoTemplate;
    @Autowired
    private IUserClient iUserClient;
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;
    @Autowired
    private IArticleClient articleClient;

    /**
     * 保存文章评论
     * @param dto 接收数据
     * @return 返回数据
     */
    @Override
    public ResponseResult saveComment(SaveCommentDto dto) {
        //1.参数校验
        if(dto==null || dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(StringUtils.isBlank(dto.getContent())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章评论不能为空！");
        }
        //2.只有登录的用户才能进行评论
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //3.校验文章是否可以评论
        if (!checkParam(dto.getArticleId())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "该文章评论权限已关闭");
        }
        //校验完成，进行评论的业务处理

        //4.评论内容不能超过140字
        if(dto.getContent().length()>140){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"评论内容不能超过140字!");
        }

        //5.评论内容需要做文本垃圾检测
        //构造评论内容审核dto
        ScanCommentContentDto contentDto=new ScanCommentContentDto();
        contentDto.setContent(dto.getContent());

        Boolean flag = iWemediaClient.commentScan(contentDto);
        if(flag){
            //远程调用，获得用户信息
            ResponseResult result = iUserClient.selectApUser(apUser);
            if(result.getCode().equals(200)){
                ApUser user = JSON.parseObject(JSON.toJSONString(result.getData()), ApUser.class);
                //构建ApComment对象
                ApComment apComment=ApComment.builder().
                        authorId(user.getId()).
                        authorName(user.getName()).
                        entryId(dto.getArticleId()).
                        type((short) 0).
                        content(dto.getContent()).
                        likes(0).
                        reply(0).
                        flag((short)0).
                        createdTime(new Date()).
                        updatedTime(new Date()).
                        status(true).build();
                //6.保存评论
                mongoTemplate.save(apComment);
            }else {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"查询用户信息失败！");
            }
        }else {
            //评论存在违规内容，返回提示信息
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章内容存在违规内容！");
        }

        //7.发送消息，增加ApArticle表文章被评论的数量
        //发送消息到kafka
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setAdd(1);
        mess.setType(UpdateArticleMess.UpdateArticleType.COMMENT);
        mess.setArticleId(dto.getArticleId());
        kafkaTemplate.send(HotArticleConstants.HOT_ARTICLE_SCORE_TOPIC,JSON.toJSONString(mess));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 评论列表的分页查询
     * @param dto 分页查询参数
     */
    @Override
    public ResponseResult loadComment(CommentDto dto) {
        //1.参数校验
        if(dto==null || dto.getArticleId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUser apUser = AppThreadLocalUtil.getUser();
        //2.数据处理
        if(dto.getIndex()==2 && apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN,"请登陆后操作");
        }
        //3.查询操作(查询评论列表，根据当前文章进行检索，按照创建时间倒序，分页查询（默认10条数据）)
        Query query = Query.query(Criteria.where("entryId")
                .is(dto.getArticleId())
                .and("createdTime")
                .lt(dto.getMinDate()))
                .with(Sort.by(Sort.Direction.DESC,"createdTime"))
                .limit(10);
        List<CommentVo> commentVoList = mongoTemplate.find(query, CommentVo.class);
        for (CommentVo commentVo : commentVoList) {
            Query query1 = Query.query(Criteria.where("commentId")
                    .is(commentVo.getId())
                    .and("authorId")
                    .is(apUser.getId()));
            ApCommentLike apCommentLike = mongoTemplate.findOne(query1, ApCommentLike.class);
            if(apCommentLike!=null){
                commentVo.setOperation((short)0);
            }else{
                commentVo.setOperation((short)1);
            }
        }
        //4.返回结果
        return ResponseResult.okResult(commentVoList);
    }

    /**
     * 用户点赞初始评论
     * @param dto 点赞评论的参数
     * @return 响应结果
     */
    @Override
    public ResponseResult liskComment(CommentLikeDto dto) {
        //1.参数校验
        if(dto==null || dto.getOperation()==null || StringUtils.isBlank(dto.getCommentId())
                || (dto.getOperation()!=1&&dto.getOperation()!=0)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.数据处理
        ApUser apUser = AppThreadLocalUtil.getUser();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询评论表
        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id")
                .is(dto.getCommentId())), ApComment.class);
        if(apComment==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //查询comment_like表的数据数据
        Query query = Query.query(Criteria.where("authorId").is(apUser.getId()).and("commentId").is(dto.getCommentId()));
        ApCommentLike one = mongoTemplate.findOne(query, ApCommentLike.class);

        if(dto.getOperation()==0){
            //点赞
            //3.添加或者删除comment_like的数据
            if(one==null){
                //构建ApCommentLike对象
                ApCommentLike like=new ApCommentLike();
                like.setCommentId(dto.getCommentId());
                like.setAuthorId(apUser.getId());
                //添加comment_like的数据
                mongoTemplate.save(like);
            }
            //增加comment的likes数量
            apComment.setLikes(apComment.getLikes()+1);
            mongoTemplate.save(apComment);
        }else {
            //4.增加或者减少comment的likes数量
            //取消点赞
            //修改like表的数据
            if(one!=null){
                mongoTemplate.remove(one);
            }

            //减少comment的likes数量
            apComment.setLikes(apComment.getLikes()-1);
            mongoTemplate.save(apComment);
        }

        //封装结果并返回
        Map<String,Object> map=new HashMap<>();
        map.put("likes",apComment.getLikes());
        return ResponseResult.okResult(map);
    }

    /**
     * 校验文章是否可以评论
     * @param articleId
     * @return
     */
    private boolean checkParam(Long articleId) {
        //是否可以评论
        ResponseResult configResult = articleClient.findArticleConfigByArticleId(articleId);
        if (!configResult.getCode().equals(200) || configResult.getData() == null) {
            return false;
        }

        ApArticleConfig apArticleConfig = JSON.parseObject(JSON.toJSONString(configResult.getData()), ApArticleConfig.class);
        if (apArticleConfig == null || !apArticleConfig.getIsComment()) {
            return false;
        }

        return true;
    }
}
